using System.Collections.Generic;

namespace Kopernikus.Parsing.Utility
{
    public class IdTable<T>
    {
        private readonly List<T> m_list = new List<T>();
        private readonly Dictionary<T, int> m_map = new Dictionary<T, int>();

        public T this[int id]
        {
            get { return m_list[id]; }
        }

        public int this[T member]
        {
            get
            {
                int id;
                if (!m_map.TryGetValue(member, out id))
                {
                    id = m_list.Count;
                    m_map.Add(member, id);
                    m_list.Add(member);
                }
                return id;
            }
        }

        public T Add(T member)
        {
            int id;
            if (!m_map.TryGetValue(member, out id))
            {
                id = m_list.Count;
                m_map.Add(member, id);
                m_list.Add(member);
                return member;
            }
            return this[id];
        }
    }
}